package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddContanctsBinding;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.base.model.entity.ContactsEntitiy;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.enterprise.AddContanctsViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.helper.OnMultiClickListener;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public class AddContanctsActivity extends AppActivity {

    private ActivityAddContanctsBinding mBinding;
    private AddContanctsViewModel mViewModel;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;
    // 二级联动数据
    public List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int positionProvince;
    private int positionCity;
    private int positionArea;
    private ContactsEntitiy data;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.actionBar.setOnBackClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View view) {
                new RoundDialog.Builder(AddContanctsActivity.this)
                        .title("温馨提示")
                        .content("信息还未填写完成，是否离开？")
                        .cancel("离开")
                        .confirm("继续编辑")
                        .contentGravity(Gravity.CENTER)
                        .cancelable(false)
                        .confirmCallback(v -> {
                        })
                        .cancelCallback(v -> {
                            finish();
                        })
                        .show();
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        mViewModel = new ViewModelProvider(this).get(AddContanctsViewModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_contancts);
        mBinding.setVariable(BR.viewModel, mViewModel);
        mBinding.setLifecycleOwner(this);
        data = (ContactsEntitiy) getIntent().getSerializableExtra("data");
        initObserver();
        initLister();
        initViewSet();
    }

    private void initObserver() {
//        mViewModel.status.observe(this, aBoolean -> mViewModel.data.getValue().setStatus(aBoolean ? "0" : "1"));
        mViewModel.areaData.observe(this, addressEntities -> {
            openAreaPop();
        });

        mViewModel.toastShow.observe(this, data -> {
            MToast.showLongToast(this, data);
        });
        mViewModel.showLoading.observe(this, type_int -> {
            switch (type_int) {
                case 1:
                    DialogHelper.showProgressDialog(getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;
            }
        });
        mViewModel.commitStatus.observe(this, s -> {
            MToast.showLongToast(this, s);
            finish();
        });
    }

    private void initLister() {
        mBinding.actionBar.setMenuFunctionClick(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View view) {
                checkData();
            }
        });
        mBinding.switchDefault.setmOnCheckedChangeListener(isChecked -> {
            mViewModel.data.getValue().setStatus(isChecked ? "0" : "1");
        });
        mBinding.itvArea.setOnWholeItemClickListener(view -> {
            if (null == mViewModel.areaData.getValue()) {
                mViewModel.getAreaData();
            } else {
                openAreaPop();
            }
        });
        mViewModel.data.setValue(data == null ? new ContactsEntitiy() : data);
        mViewModel.path.setValue(data == null ? "" : data.getProvinceName() + data.getCityName() + data.getAreaName());
    }

    private void initViewSet() {
        mBinding.itvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itvPostCode.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.switchDefault.setChecked("0".equals(mViewModel.data.getValue().getStatus()) ? true : false);
        mBinding.actionBar.setTitle(null == data ? "新增联系人" : "编辑联系人");
    }

    /**
     * 数据检验
     */
    private void checkData() {
        if (TextUtils.isEmpty(mBinding.itvCName.getContent())) {
            MToast.showToast(AddContanctsActivity.this, "请输入联系人");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvPhone.getContent())) {
            MToast.showToast(AddContanctsActivity.this, "请输入联系电话");
            return;
        } else if (!CheckUtils.checkMobile(mBinding.itvPhone.getContent())) {
            MToast.showToast(AddContanctsActivity.this, "请输入正确的电话格式");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvArea.getContent())) {
            MToast.showToast(AddContanctsActivity.this, "请选择所在地区");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvAddress.getContent())) {
            MToast.showToast(AddContanctsActivity.this, "请输入详细地址");
            return;
        }
        //发布类型 0个人  1企业  2团队
        Integer publishType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (0 == publishType) {
            mViewModel.data.getValue().setUserNo(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
        } else if (1 == publishType) {
            mViewModel.data.getValue().setCompanyNo(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        } else if (2 == publishType) {
            mViewModel.data.getValue().setTeamNo(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        }
        mViewModel.data.getValue().setPublishType(publishType);
        mViewModel.submitData(0);
    }

    private void openAreaPop() {
        if (isLoaded) {
            showAreaPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    /**
     * 地区弹窗
     */
    public void showAreaPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(AddContanctsActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                positionArea = options3;
                mViewModel.data.getValue().setAreaCode(opt3.get(options1).get(options2).get(options3).getNo());
                mViewModel.data.getValue().setAreaName(areaName);
            }
            String content = mViewModel.areaData.getValue().get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            mBinding.itvArea.setContent(content);
            positionProvince = options1;
            positionCity = options2;
            mViewModel.data.getValue().setProvinceName(mViewModel.areaData.getValue().get(options1).getName());
            mViewModel.data.getValue().setProvinceCode(mViewModel.areaData.getValue().get(options1).getId());
            mViewModel.data.getValue().setCityName(opt2.get(options1).get(options2).getName());
            mViewModel.data.getValue().setCityCode(opt2.get(options1).get(options2).getNo());
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        cityOption.setPicker(mViewModel.areaData.getValue(), opt2, opt3);
        cityOption.setSelectOptions(positionProvince, positionCity, positionArea);
        cityOption.show();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showAreaPop();
                    isLoaded = true;
                    thread = null;
                    break;
                default:
                    break;
            }
        }
    };


    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < mViewModel.areaData.getValue().size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (mViewModel.data.getValue() != null && mViewModel.data.getValue().getProvinceCode() != null && mViewModel.data.getValue().getProvinceCode().equals(mViewModel.areaData.getValue().get(x).getNo())) {
                positionProvince = x;
            }
            opt2.add(mViewModel.areaData.getValue().get(x).getChildren());
            for (int i = 0; i < mViewModel.areaData.getValue().get(x).getChildren().size(); i++) {
                cityList.add(mViewModel.areaData.getValue().get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (mViewModel.areaData.getValue().get(x).getChildren().get(i).getChildren() == null
                        || mViewModel.areaData.getValue().get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(mViewModel.areaData.getValue().get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (mViewModel.data.getValue() != null) {
            if (mViewModel.data.getValue().getCityCode() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (mViewModel.data.getValue().getCityCode().equals(mViewModel.areaData.getValue().get(positionProvince).getChildren().get(x2).getNo())) {
                        positionCity = x2;
                        break;
                    }
                }
            }
            if (mViewModel.data.getValue().getAreaCode() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (mViewModel.data.getValue().getAreaCode().equals(mViewModel.areaData.getValue().get(positionProvince).getChildren().get(positionCity).getChildren().get(x3).getNo())) {
                        positionArea = x3;
                        break;
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public static void startactivity(Context mContext) {
        Intent mIntent = new Intent(mContext, AddContanctsActivity.class);
        mContext.startActivity(mIntent);
    }

    public static void startactivity(Context mContext, ContactsEntitiy data) {
        Intent mIntent = new Intent(mContext, AddContanctsActivity.class);
        mIntent.putExtra("data", (Serializable) data);
        mContext.startActivity(mIntent);
    }
}
